package feign;

import com.chenfan.infra.constants.CommonBeanConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 传递当前上下文中的请求header信息到feign
 */
@Slf4j
public class RequestHeaderForwardFeignInterceptorConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (RequestContextHolder.getRequestAttributes() !=null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String[] headNames = new String[]{CommonBeanConstants.AUTHORIZATION,"app_key","currentUser"};
            for (String headName : headNames) {
                setHeader(requestTemplate, request, headName);
            }
        }
    }
    private void setHeader(RequestTemplate requestTemplate, HttpServletRequest request, String headName) {
        if (!requestTemplate.headers().keySet().contains(headName)) {
            // todo urldecode [RequestHeaderForwardFeignInterceptorConfig][设置feign请求header][headName=====currentUser][value======%7B%22account%22%3A%22%E5%BC%A0%E8%AF%97%E5%A9%B7%22%2C%22companyId%22%3A4%2C%22departmentId%22%3A1356172418615349250%2C%22roleIds%22%3A%221376417338219302913%22%2C%22tenantId%22%3A1%2C%22userId%22%3A1603215851659522050%7D
            // log.info("[RequestHeaderForwardFeignInterceptorConfig][设置feign请求header][headName====={}][value======{}]",headName,request.getHeader(headName));
            requestTemplate.header(headName, request.getHeader(headName));
        }
    }
}
